//
//  HomeViewController.m
//  FoodCorner
//
//  Created by Summer on 16/2/28.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeViewController.h"
#import "HomeDataHelper.h"
#import "HomeListCell.h"
#import "MainListModel.h"
#import "ShufflingView.h"
#import "SearchViewController.h"
#import "FoodPracticeViewController.h"
#import "CookBookTableController.h"
#import "DataMemoryTools.h"
#import "FoodNameViewController.h"
#import <MJRefresh/MJRefresh.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import <SDAutoLayout/UITableView+SDAutoTableViewCellHeight.h>
#import <SDWebImage/UIImageView+WebCache.h>
#define kPAGE 1
@interface HomeViewController ()<UIScrollViewDelegate,UISearchBarDelegate>
@property (nonatomic,assign)NSInteger currtentPage;
@property (nonatomic,strong)ShufflingView *shufflingView;
@property (nonatomic,strong)UISearchController *searchController;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [DataMemoryTools openDataBase];
    self.shufflingView = [[ShufflingView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 175)];
    self.tableView.tableHeaderView = self.shufflingView;
    self.shufflingView.scrollView.delegate = self;
    [self viewBlurEffect];
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerClass:[HomeListCell class] forCellReuseIdentifier:@"cellID"];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(AddControllerAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"tabbar3"] style:(UIBarButtonItemStylePlain) target:self action:@selector(foodListMethod)];
    
    //self.navigationItem.titleView = self.searchController.searchBar;
    //[self searchController];
    [self relodData];
    [self refreshDataWithHeader];
    [self refreshDataWithFooter];
}
#pragma mark - 添加菜单的页面方法
- (void)AddControllerAction
{
    FoodNameViewController *nameVC = [[FoodNameViewController alloc]init];
    UINavigationController *nameNC = [[UINavigationController alloc]initWithRootViewController:nameVC];
    [self presentViewController:nameNC animated:YES completion:nil];
}
#pragma mark - 菜单列表
- (void)foodListMethod
{
    CookBookTableController *cookVC = [[CookBookTableController alloc]init];
    [self.navigationController pushViewController:cookVC animated:YES];
}
#pragma mark - 搜索菜品的页面

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return [[HomeDataHelper sharedHomeDataHelper] numberOfDatas];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    
    // Configure the cell...
    MainListModel *model = [[HomeDataHelper sharedHomeDataHelper] modelOfIndex:indexPath.row];
    cell.model = model;
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainListModel *model = [[HomeDataHelper sharedHomeDataHelper] modelOfIndex:indexPath.row];
    
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[HomeListCell class] contentViewWidth:[self cellContentViewWith]];
}
- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 9.2) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}
#pragma mark - 点击cell出现的点击事件

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoodPracticeViewController  *foodPVC = [[FoodPracticeViewController alloc]init];
    UINavigationController *foodNC = [[UINavigationController alloc]initWithRootViewController:foodPVC];
    foodPVC.listModel = [[HomeDataHelper sharedHomeDataHelper] modelOfIndex:indexPath.row];
    [self presentViewController:foodNC animated:YES completion:nil];
}
#pragma mark -------加载数据。实现刷新
/**
 *  @author Summer
 *
 *  加载数据
 */
- (void)relodData
{
    [[HomeDataHelper sharedHomeDataHelper] findAllDynamicWithLimitNumber:10 success:^{
        [self.tableView reloadData];
    } failed:^(NSString *massage) {
        [self reloadDataFailed:massage];
    }];
}
/**
 *  @author Summer
 *
 *  下拉刷新，实现数据的刷新
 */
- (void)refreshDataWithHeader
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshDataWithPullDownHeader)];
    
    // 设置文字
    [header setTitle:@"Pull down to refresh" forState:MJRefreshStateIdle];
    [header setTitle:@"Release to refresh" forState:MJRefreshStatePulling];
//    [header setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
    
    // 设置字体
    header.stateLabel.font = [UIFont systemFontOfSize:15];
    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    
    // 设置颜色
    header.stateLabel.textColor = [UIColor redColor];
    header.lastUpdatedTimeLabel.textColor = [UIColor blueColor];
    
    // 马上进入刷新状态
    [header beginRefreshing];
    
    // 设置刷新控件
    self.tableView.mj_header = header;
}
/**
 *  @author Summer
 *
 *  下拉刷新，方法实现
 */
- (void)refreshDataWithPullDownHeader
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        [self.tableView.mj_header endRefreshing];
    });
}
/**
 *  @author Summer
 *
 *  上拉刷新，实现数据的更新
 */
- (void)refreshDataWithFooter
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshDataWithPullUpFooter)];
    
    // 设置文字
    [footer setTitle:@"Pull down to refresh" forState:MJRefreshStateIdle];
    [footer setTitle:@"Release to refresh" forState:MJRefreshStatePulling];
//    [footer setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
    
    // 设置字体
    footer.stateLabel.font = [UIFont systemFontOfSize:15];
    // 设置颜色
    footer.stateLabel.textColor = [UIColor redColor];
    // 马上进入刷新状态
    [footer beginRefreshing];
    
    // 设置刷新控件
    self.tableView.mj_footer = footer;
}
/**
 *  @author Summer
 *
 *  上拉刷新，方法实现
 */
- (void)refreshDataWithPullUpFooter
{
    _currtentPage += 20;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[HomeDataHelper sharedHomeDataHelper]findAllDynamicWithLimitNumber:_currtentPage success:^{
            [self.tableView reloadData];
        } failed:^(NSString *massage) {
            [self reloadDataFailed:massage];
        }];
        [self.tableView.mj_footer endRefreshing];
    });
    
}
- (void)reloadDataFailed:(NSString *)massage
{
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    progressHUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
    progressHUD.labelText = [NSString stringWithFormat:@"请求失败错误%@",massage];
    progressHUD.animationType = MBProgressHUDAnimationFade;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [progressHUD hide:YES];
    });

}
#pragma mark---- 轮播图代理方法实现
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self reloadImage];
    self.shufflingView.scrollView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width , 0);
    
    self.shufflingView.pageControl.currentPage = _shufflingView.currentImageIndex;
}
-(void)reloadImage
{
    CGPoint offset = self.shufflingView.scrollView.contentOffset;
    
    if (offset.x > [UIScreen mainScreen].bounds.size.width) {
        self.shufflingView.currentImageIndex = (self.shufflingView.currentImageIndex + 1) % (self.shufflingView.ImgArray.count);
    }else if (offset.x <[UIScreen mainScreen].bounds.size.width)
    {
        self.shufflingView.currentImageIndex = (self.shufflingView.currentImageIndex + (int)(self.shufflingView.ImgArray.count -1)) % (self.shufflingView.ImgArray.count);
    }
    
    int leftImageIndex,rightImageIndex;
    
    self.shufflingView.currentImageIndex = (self.shufflingView.currentImageIndex + 1) % (self.shufflingView.ImgArray.count);
    
    [self.shufflingView.centerImageView sd_setImageWithURL:[NSURL URLWithString:self.shufflingView.ImgArray[self.shufflingView.currentImageIndex]]];
    
    rightImageIndex = (self.shufflingView.currentImageIndex + 1) % (self.shufflingView.ImgArray.count);
    leftImageIndex = (self.shufflingView.currentImageIndex + (int)(self.shufflingView.ImgArray.count -1)) % (self.shufflingView.ImgArray.count);
    
    [_shufflingView.leftImageView sd_setImageWithURL:[NSURL URLWithString:self.shufflingView.ImgArray[leftImageIndex]]];
    // NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.ImgArray[rightImageIndex]]];
    
    [_shufflingView.rightImageView sd_setImageWithURL:[NSURL URLWithString:self.shufflingView.ImgArray[rightImageIndex]]];
    
    self.shufflingView.scrollView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width , 0);
    
    self.shufflingView.pageControl.currentPage = _shufflingView.currentImageIndex;
    
}
#pragma mark ----添加视图模糊效果，增加视觉效果
- (void)viewBlurEffect
{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    imageView.image = [UIImage imageNamed:@"placeholder"];
    //毛玻璃效果
    UIVisualEffectView *visualView =[[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:(UIBlurEffectStyleLight)]];
    visualView.alpha = 0.9;
    visualView.frame=[UIScreen mainScreen].bounds;
    
    [imageView addSubview:visualView];
    
    self.tableView.backgroundView = imageView;
    
    self.tableView.separatorEffect = [UIBlurEffect effectWithStyle:(UIBlurEffectStyleDark)];
}


@end
